﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;
using Wechat.TenpayV3;

namespace QuDao
{
    /// <summary>
    /// 数据表base_wx_app关联的业务对象，处理该表相关的业务逻辑
    /// </summary>
    public sealed partial class WxAppBO : SingletonBase<WxAppBO>
    {
        readonly AppSettings appSettings;
        readonly IFreeSql fsql;
        List<WxApp> list;

        public WxAppBO() : base()
        {
            appSettings = AppSettings.Load();
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
            Reload();
        }

        public int Reload()
        {
            list = fsql.Select<WxApp>().Take(1000).ToList();
            return list.Count;
        }

        /// <summary>
        /// 获取微信应用
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public WxApp GetItem(string id, bool isFromDB = false)
        {
            if(isFromDB)
            {
                var item = fsql.Select<WxApp>().Where(a => a.WxAppID == id).ToOne();
                return item;
            }
            else
            {
                if (string.IsNullOrEmpty(id)) return default;
                var item = list.Find(p => p.WxAppID == id);

                if (item == null)
                {
                    item = fsql.Select<WxApp>().Where(a => a.WxAppID == id).ToOne();
                    if (item != null) list.Add(item); //如果有新增的应用，不用刷新缓存直接从数据库获取
                }
                return item;
            }
        }

        /// <summary>
        /// 更新访问令牌数据
        /// </summary>
        /// <param name="token">访问令牌</param>
        /// <param name="expiredTime">过期时间</param>
        public void UpdateToken(string id, string token, DateTime expiredTime)
        {
            var item = GetItem(id, true);
            if (item == null) return;

            item.AccessToken = token;
            item.TokenExpiredTime = expiredTime;

            fsql.Update<WxApp>(id)
                .Set(a => a.AccessToken, token)
                .Set(a => a.TokenExpiredTime, expiredTime)
                .ExecuteAffrows();
        }

        /// <summary>
        /// 获取微信应用数据列表
        /// </summary>
        /// <returns></returns>
        public List<WxApp> GetList(bool isFromDB = false)
        {
            if(isFromDB)
            {
                list = fsql.Select<WxApp>().Take(1000).ToList();
            }

            return list;
        }

        public Dictionary<string, string> GetDic()
        {
            var dic = new Dictionary<string, string>();
            var list = GetList(true);

            foreach (var item in list)
            {
                dic.Add(item.WxAppID, item.WxAppName);
            }

            return dic;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<T> Query<T>(PagingRequest req)
        {
            if (req == null) throw new AppException("查询数据不能为空");

            var select = fsql.Select<WxApp>();
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    //case "WXAppID":
                    //    select.Where(a => a.WXAppID == int.Parse(item.Value));
                    //    break;
                    //case "WXAppName":
                    //    select.Where(a => a.WXAppName.Contains(item.Value));
                    //    break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.WxAppID);//默认排序
            }

            var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<T>();
            return new PagingResult<T>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }

        public PagingResult<WxApp> Query(PagingRequest req)
        {
            return Query<WxApp>(req);
        }

    }
}
